/**
 * 列选择
 */

import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Popover, Tree } from 'antd';
import _ from 'lodash';
import { PrimaryGhostC } from '../../../../../comps';
import style from './index.less';

export default class SetColumns extends PureComponent {
  static defaultProps = {
    checkedKeysInfo: [], // 默认勾选
    columns: [], // 数据源
    onChange: () => {}, // 选中变更事件
    selectOnChange: () => {}, // 数据勾选事件
    context: '',
  };
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectedKeys: [],
      checkedKeysInfo: [],
    };
  }
  componentDidMount() {
    const { checkedKeysInfo } = this.props;
    this.setState({ checkedKeysInfo });
  }

  handleVisibleChange = (visible) => {
    this.setState({
      visible: visible,
    });
    this.props.onChange();
  };

  onSelect = (checkedKeysInfo) => {
    this.setState(
      {
        checkedKeysInfo,
      },
      () => this.handleOk(checkedKeysInfo),
    );
  };

  handleOk = (checkedKeysInfo) => {
    const { columns } = this.props;
    let newColumnsInfo = _.cloneDeep(columns);
    newColumnsInfo.map((item) => {
      item.display = false;
      checkedKeysInfo.map((item1) => {
        if (item1 == item.key) {
          item.display = true;
        }
      });
    });
    this.props.selectOnChange(newColumnsInfo, checkedKeysInfo);
  };

  render() {
    const { columns, context } = this.props;
    const content = (
      <div>
        <Tree treeData={columns} checkable defaultExpandAll checkedKeys={this.state.checkedKeysInfo} onCheck={this.onSelect} />
      </div>
    );
    return (
      <div>
        <Popover placement='leftTop' content={content} trigger='click' visible={this.state.visible} overlayClassName={style.shstyle} onVisibleChange={this.handleVisibleChange}>
          {/* <div>列选择<Icon type="right" style={{ float: 'right', marginTop: '4px' }} /></div> */}
          {context ? context : <PrimaryGhostC title='列选择' style={{ marginBottom: '10px' }} />}
        </Popover>
      </div>
    );
  }
}
SetColumns.propsTypes = {
  checkedKeysInfo: PropTypes.array, // 默认勾选
  columns: PropTypes.array, // 数据源
  onChange: PropTypes.func, // 选中变更事件
  selectOnChange: PropTypes.func, // 数据勾选事件
};
